# authentication/views.py

from rest_framework import generics, permissions, status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken
from .serializers import RegisterSerializer, LoginSerializer
from product.serializers import UserSerializer, UserProfileSerializer  # 正确的导入路径
from django.contrib.auth.models import User
from product.models import UserProfile
from rest_framework.decorators import api_view, permission_classes

class RegisterView(generics.CreateAPIView):
    queryset = User.objects.all()
    permission_classes = [permissions.AllowAny]
    serializer_class = RegisterSerializer
    
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        
        # 获取用户详细信息
        user_profile = UserProfile.objects.get(user=user)
        
        # 生成token
        refresh = RefreshToken.for_user(user)
        
        # 构建符合前端要求的响应格式
        response_data = {
            "code": 200,
            "message": "success",
            "data": {
                "token": str(refresh.access_token),
                "userInfo": {
                    "id": user.id,
                    "username": user.username,
                    "name": user.username,  # 使用username作为name
                    "avatar": user_profile.avatar.url if user_profile.avatar else "",
                    "email": user.email,
                    "phone": user_profile.phone,
                    "bio": user_profile.bio or ""
                }
            }
        }
        
        return Response(response_data, status=status.HTTP_201_CREATED)

class LoginView(APIView):
    def post(self, request, *args, **kwargs):
        serializer = LoginSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            user = serializer.validated_data
            refresh = RefreshToken.for_user(user)
            
            # 获取用户详细信息
            user_profile = UserProfile.objects.get(user=user)
            
            # 构建符合前端要求的响应格式
            response_data = {
                "code": 200,
                "message": "success",
                "data": {
                    "token": str(refresh.access_token),
                    "userInfo": {
                        "id": user.id,
                        "username": user.username,
                        "name": user.username,  # 使用username作为name
                        "avatar": user_profile.avatar.url if user_profile.avatar else "",
                        "email": user.email,
                        "phone": user_profile.phone,
                        "bio": user_profile.bio or ""
                    }
                }
            }
            
            return Response(response_data)
        return Response({
            "code": 400,
            "message": serializer.errors,
            "data": None
        }, status=status.HTTP_400_BAD_REQUEST)

# 用户信息API
@api_view(['GET', 'PUT'])
@permission_classes([permissions.IsAuthenticated])
def user_info_view(request):
    if request.method == 'GET':
        # 获取用户信息
        user = request.user
        try:
            user_profile = UserProfile.objects.get(user=user)
            
            # 构建用户统计信息
            stats = {
                "published": user.products.count(),  # 用户发布的商品数量
                "sold": user.products.filter(status='已售').count(),  # 已售出的商品数量
                "followers": 0  # 需要根据关注系统实现
            }
            
            response_data = {
                "code": 200,
                "data": {
                    "id": user.id,
                    "username": user.username,
                    "avatar": user_profile.avatar.url if user_profile.avatar else "",
                    "email": user.email,
                    "phone": user_profile.phone,
                    "bio": user_profile.bio or "",
                    "stats": stats
                }
            }
            
            return Response(response_data)
            
        except UserProfile.DoesNotExist:
            return Response({
                "code": 404,
                "message": "用户信息不存在",
                "data": None
            }, status=status.HTTP_404_NOT_FOUND)
    
    elif request.method == 'PUT':
        # 更新用户信息
        user = request.user
        try:
            user_profile = UserProfile.objects.get(user=user)
            
            # 更新用户基本信息
            if 'username' in request.data:
                user.username = request.data['username']
                user.save()
            
            # 更新用户扩展信息 - 处理文件上传
            if 'avatar' in request.FILES:
                # 处理文件上传
                user_profile.avatar = request.FILES['avatar']
            elif 'avatar' in request.data:
                # 处理普通文本格式的头像URL（如果前端发送的是URL而不是文件）
                user_profile.avatar = request.data['avatar']
                
            if 'email' in request.data:
                user.email = request.data['email']
                user.save()
            if 'phone' in request.data:
                user_profile.phone = request.data['phone']
            if 'bio' in request.data:
                user_profile.bio = request.data['bio']
            
            user_profile.save()
            
            # 返回更新后的用户信息
            stats = {
                "published": user.products.count(),
                "sold": 0,
                "followers": 0
            }
            
            response_data = {
                "code": 200,
                "data": {
                    "id": user.id,
                    "username": user.username,
                    "avatar": user_profile.avatar.url if user_profile.avatar else "",
                    "email": user.email,
                    "phone": user_profile.phone,
                    "bio": user_profile.bio or "",
                    "stats": stats
                }
            }
            
            return Response(response_data)
            
        except UserProfile.DoesNotExist:
            return Response({
                "code": 404,
                "message": "用户信息不存在",
                "data": None
            }, status=status.HTTP_404_NOT_FOUND)

# 根据用户ID获取用户信息API
@api_view(['GET'])
@permission_classes([permissions.AllowAny])  # 允许匿名访问，因为商品详情页需要显示卖家信息
def get_user_by_id_view(request, user_id):
    try:
        user = User.objects.get(id=user_id)
        try:
            user_profile = UserProfile.objects.get(user=user)
            
            response_data = {
                "code": 200,
                "data": {
                    "id": user.id,
                    "username": user.username,
                    "avatar": user_profile.avatar.url if user_profile.avatar else "",
                    "email": user.email,
                    "phone": user_profile.phone,
                    "bio": user_profile.bio or ""
                }
            }
            
            return Response(response_data)
            
        except UserProfile.DoesNotExist:
            return Response({
                "code": 404,
                "message": "用户信息不存在",
                "data": None
            }, status=status.HTTP_404_NOT_FOUND)
            
    except User.DoesNotExist:
        return Response({
            "code": 404,
            "message": "用户不存在",
            "data": None
        }, status=status.HTTP_404_NOT_FOUND)